﻿using System;
using System.Collections.Generic;
using System.Linq;
using ShuttleBus.AdminMessages;
using ShuttleBus.Subscriptions;
using ShuttleBus.Transports.AmazonSqs.Clients;

namespace ShuttleBus.Transports.AmazonSqs
{
    public class SnsSubscriptionRepository : ISubscriptionRepository
    {
        private readonly ISnsClient _snsClient;
        private readonly ISqsClient _sqsClient;
        private readonly Uri _tranportUri;

        public SnsSubscriptionRepository(ISnsClient snsClient, ISqsClient sqsClient, Uri tranportUri)
        {
            _snsClient = snsClient;
            _sqsClient = sqsClient;
            _tranportUri = tranportUri;
        }

        public IEnumerable<Subscription> GetSubscribersOf(Message message)
        {
            var messageType = message.GetType();
            return _snsClient.QuerySubscriptions(messageType.Name)
                .Select(s =>
                {
                    var endpoint = s.Endpoint;
                    var uri = string.Format("sqs://{0}", endpoint.Substring(endpoint.LastIndexOf(':') + 1));
                    return new Subscription(new Uri(uri), messageType);
                });
        }

        public void Add(AddSubscriptionMessage message)
        {
            var subscription = message.ToSubscription();

            var queueArn = _sqsClient.GetQueueArn(_tranportUri.Host);

            var topics = _snsClient.QueryTopics(subscription.Name).ToList();

            if (topics.Count == 0)
            {
                topics.Add(_snsClient.Create(subscription.Name));
            }

            _snsClient.Subscribe(queueArn, topics);
        }
    }
}
